package top.seefly.javase.guava;

import java.util.LinkedList;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 看看我能不能实现一个漏桶算法 核心思想： 维护一个固定大小的容器，消费者可以按照任何频率将任务放入容器中 服务提供者只按照固定频率从容器中取任务执行
 *
 * @author liujianxin
 * @date 2021/4/16 17:09
 */
public class LeakyBucket {
    
    private ReentrantLock lock = new ReentrantLock();
    
    private LinkedList<Runnable> bucket = new LinkedList<>();
    
    private int maxBucketSize = 16;
    
    private int duration = 1000;// 1000ms 一次
    
    private long lastPickTime = System.currentTimeMillis(); // 上次取任务时间
    
    public boolean put(Runnable task) {
        lock.lock();
        try {
            if (bucket.size() < maxBucketSize) {
                bucket.add(task);
                return true;
            } else {
                System.out.println("满了！！！");
                return false;
            }
        } finally {
            lock.unlock();
        }
    }
    
    public Runnable take() {
        lock.lock();
        try {
            long current = System.currentTimeMillis();
            Runnable task = null;
            if (duration < current - lastPickTime) {
                task = bucket.poll();
                if (task != null) {
                    lastPickTime = current;
                }
            }
            return task;
        } finally {
            lock.unlock();
        }
        
    }
}
